//
//  _iOSUtils_Addtions.m
//  iOSUtils
//
//  Created by HJC on 11-9-9.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "_iOSUtils_OtherAddtions.h"
#import "_iOSUtils_SmallFuns.h"


@implementation UIColor(_iOSUtils_Addtions)


inline static NSInteger fromHex2(unichar c0, unichar c1)
{
	NSInteger val0 = NSIntegerFromHexChar(c0);
	NSInteger val1 = NSIntegerFromHexChar(c1);
	return val0 * 16 + val1;
}


+ (UIColor*) colorFromString:(NSString*)string
{
    if ([string hasPrefix:@"#"])
    {
        string = [string substringFromIndex:1];
    }
    
    NSInteger red = 0;
    NSInteger green = 0;
    NSInteger blue = 0;
    
    if ([string length] >= 2)
    {
        red = fromHex2([string characterAtIndex:0], [string characterAtIndex:1]);
    }
    if ([string length] >= 4)
    {
        green = fromHex2([string characterAtIndex:2], [string characterAtIndex:3]);
    }
    if ([string length] >= 6)
    {
        blue = fromHex2([string characterAtIndex:4], [string characterAtIndex:5]);
    }
    return [UIColor colorWithRed:(red / 255.0f)
                           green:(green / 255.0f)
                            blue:(blue / 255.0f)
                           alpha:1.0];
}


@end


////////////////////////////////////////////////////////////////////////
@implementation NSDictionary(Addtions)

+ (NSDictionary *)dictionaryWithContentsOfData:(NSData *)data
{
    CFPropertyListRef plist =  CFPropertyListCreateFromXMLData(kCFAllocatorDefault, (CFDataRef)data, 
                                                               kCFPropertyListImmutable, 
                                                               NULL); 
    if(plist == nil) 
    {
        return nil; 
    }
    
    if ([(id)plist isKindOfClass:[NSDictionary class]]) 
    { 
        return [(NSDictionary *)plist autorelease]; 
    } 
    
    CFRelease(plist); 
    return nil; 
}

@end


//////////////////////////////////
@implementation NSMutableArray(_iOSUtils_Addtions)

- (void) moveObjectAtIndex:(NSInteger)atIndex toIndex:(NSInteger)toIndex
{
    NSObject* object = [self objectAtIndex:atIndex];
    [object retain];
    
    [self removeObjectAtIndex:atIndex];
    [self insertObject:object atIndex:toIndex];
    
    [object release];
}


- (void) reverse
{
    NSInteger count = [self count];
    NSInteger halfCount = [self count] / 2;
    for (NSInteger idx = 0; idx < halfCount; idx++)
    {
        [self exchangeObjectAtIndex:idx withObjectAtIndex:(count - 1 - idx)];
    }
}

@end


////////////////////////////////////////////////////////////////////////

@implementation NSFileManager(_iOSUtils_Addtions)

+ (NSString*) documentPath
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	return [paths objectAtIndex:0];
}


+ (NSString*) resourcePath
{
	return [[NSBundle mainBundle] resourcePath];
}


+ (BOOL) letDirectoryExistsAtPath:(NSString*)filePath
{
    NSFileManager* fileManager = [NSFileManager defaultManager];
	if ([fileManager fileExistsAtPath:filePath])
	{
		return YES;
	}
	
	NSArray* array = [filePath componentsSeparatedByString:@"/"];
	[fileManager changeCurrentDirectoryPath:@"/"];
	
	for (NSString* string in array)
	{
		if ([string length] > 0)
		{
			BOOL isDirectory = TRUE;
			if (![fileManager fileExistsAtPath:string isDirectory:&isDirectory] || 
				!isDirectory)
			{
				[fileManager createDirectoryAtPath:string 
                       withIntermediateDirectories:YES 
                                        attributes:nil 
                                             error:nil];
			}
			[fileManager changeCurrentDirectoryPath:string];
		} 
	}
    
	return [fileManager fileExistsAtPath:filePath];
}




static TraverseRetureType TraversePath(NSFileManager* fileManager, 
                                       NSString* basePath, 
                                       NSString* refPath, 
                                       BOOL recursive,
                                       TraversePathCallBackType callBack,
                                       void* context)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    
    NSString* path = [basePath stringByAppendingPathComponent:refPath];
    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
    
    TraversePathInfo travPathInfo;
    travPathInfo.basePath = basePath;
    
    for (NSString* subPath in array)
    {
        NSString* fullPath = [path stringByAppendingPathComponent:subPath];
        BOOL isDirectory = NO;
        if ([fileManager fileExistsAtPath:fullPath isDirectory:&isDirectory])
        {
            NSString* curPath = [refPath stringByAppendingPathComponent:subPath];
            travPathInfo.refPath = curPath;
            travPathInfo.isDirectory = isDirectory;
            
            TraverseRetureType retureType = callBack(travPathInfo, context);            
            if (retureType == TraverseRetureType_Continue)
            {
                if (isDirectory && recursive)
                {
                    retureType = TraversePath(fileManager, basePath, curPath, recursive, callBack, context);
                }
            }
            
            if (retureType == TraverseRetureType_StopTraverseAll)
            {
                [pool release];
                return TraverseRetureType_StopTraverseAll;
            }
        }
    }
    
    [pool release];
    return TraverseRetureType_Continue;
}



+ (void) traversePath:(NSString*)path 
            recursive:(BOOL)recursive
             callBack:(TraversePathCallBackType)callBack
              context:(void*)context
{
    NSFileManager* fileManager = [NSFileManager defaultManager];
    TraversePath(fileManager, path, @"", recursive, callBack, context);
}


@end

